package com.atguigu.crowd.util;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 */
public class CrowdUtil {
    /**
     *  对明文字符串进行md5加密
     * @param source 传入的字符串
     * @return
     */
    public static String md5(String source) {
        if (source == null || source.length() == 0) {
            // 如果不是有效字符串抛出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        String algorithm = "md5";
        try {
            MessageDigest instance = MessageDigest.getInstance(algorithm);

            // 获取明文字符串对应的字节数组
            byte[] input = source.getBytes();

            // 执行加密
            byte[] output = instance.digest(input);

            // 创建BigInteger对象
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum, output);

            // 按照16进制将bigInteger的值转成字符串
            int radix = 16;
            String encode = bigInteger.toString(radix);
            return encode;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 判断当前请求是否为ajax的请求
     *
     * @param request
     * @return true:当前是ajax请求
     * false:当前请求不是ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        String xHeader = request.getHeader("X-Requested-With");


        return (accept != null && accept.contains("application/json"))
                ||
                (xHeader != null && xHeader.equals("XMLHttpRequest"));


    }

}
